<?php

namespace Common\Logic;

/**
 * 商品类 处理价格计算和运费问 
 */ 
class FeeLogic
{

    const SHOP_TABLE = "shop";
    const GOODS_TABLE = "goods";

    const CACHE_KEY_POST_FEE = "CACHE_KEY_POST_FEE_";

    /**
     * 获取店铺的运费设置
     * @param shop_id
     * @return mix [
     *      "fee_freepost" => 满多少免邮
     *      "default_postfee" => 默认几多邮费
     * ]
     */ 
    public static function getShopPostFeeSettings( $shop_id = 0 )
    {
        // $cache = S(self::CACHE_KEY_POST_FEE.$shop_id);
        $cache = NULL;

        $logText = "\n[GETCONF]";

        $logText .= "\n[PARAMS]".json_encode(func_get_args());

        $logText .= "\n[CACHE]".json_encode($cache);

        if( !$cache )
        {
            $cache = M(self::SHOP_TABLE)->where([
                "id" => $shop_id
            ])->field("fee_freepost,default_postfee,first_weight,second_weight,add_postfee")->find();
            $logText .= "\n[DBCONF]".json_encode($cache);
            if( $cache )
            {
                S(self::CACHE_KEY_POST_FEE.$shop_id,$cache);
            }
        }
        doLog($logText,'postfee');
        return $cache;        
    }

    /**
     * 删除邮费缓存 
     * @param shop_id
     */ 
    public static function rmPostFeeCache($shop = 0)
    {
        return S(self::CACHE_KEY_POST_FEE.$shop_id,null);
    }

    /**
     * 根据商品总重量计算邮费(以商铺为单位)     
     * @param shop_id 商铺id
     * @param weight 商品总重量 克
     * @param goods_fee 商品总价
     * @return float
     */ 
    public static function getPostFee( $shop_id = 0, $weight = 0, $goods_fee = 0 )
    {
        // if( $weight <= 0 )
        // {
        //     return 0;
        // }

        $conf = self::getShopPostFeeSettings($shop_id);
        
        $logText = "\n[PARAMS]".json_encode(func_get_args());

        $logText .= "\n[CONF]".json_encode($conf);

        doLog($logText,'postfee');

        if(!$conf) return 0;
		
        if( $conf['fee_freepost'] > 0 && $goods_fee >= $conf['fee_freepost'] )
        {
            return 0;
        }

        #计算首重价格
        $f_price = $conf['default_postfee'];

        #如果续重为0或者续费为0
        if( $weight <= $conf['first_weight'] || $conf['second_weight'] < 1 || $conf['add_postfee'] < 0 )
        {
            return $f_price;
        }

        #计算续重
        $weight = $weight - $conf['first_weight'];
        $m_w = ceil( $weight /  $conf['second_weight'] );

        if( $m_w <= 0 )
            return $f_price;
        
        return $f_price + $m_w * $conf['add_postfee'];
    }

    /**(暂时不用)
     * 根据商品计算费用(以商铺为单位) （如果是不同的店铺，那么会取第一个店铺的商品进行计算其他的忽略）
     * @param goods 支持同店铺多商品和任意单商品
     * @param shop_id 指定店铺（默认取第一个商品的店铺）
     * @param user_id 指定用户 会返回用户的可用积分
     * @param invalid_chk 是否检查商品是否合法，检查的时候不存在时抛出错误，否则会忽略
     * @return mix
     * @throw exception
     */ 
    public static function getFeeForShop( $goods = [], $shop_id = null, $user_id= 0, $invalid_chk = true )
    {
        if( empty($goods) )
            return 0;
        #判断是多商品还是单商品
        if( isset($goods['goods_id']) )
        {
            $goods = [$goods];
        }
        $total_amount = 0; // 订单总价(商品+运费)
        $order_amount = 0;// 应付金额（订单总价-优惠-抵扣）
        $shipping_price = 0;// 物流费
        $goods_price = 0;// 商品总价
        $goods_weight = 0;// 商品总重量
        $cut_fee = 0;// 共节约多少钱
        $anum = 0;// 商品总共数量
        $pay_points_money = 0;// 积分抵消金额
        $all_pay_point = 0;// 所有抵扣需要扣除的积分
        $order_amount_uncharge = 0;

        $GoodsModel = M(self::GOODS_TABLE);
        $GoosField = "goods_id,weight,shop_price,market_price,is_free_shipping,exchange_integral,prom_type,prom_id,is_on_sale";
        $cartModel = M('cart');
        foreach( $goods as $k => $v )
        {
            if( is_null($shop_id) )
            {
                $shop_id = $v['shop_id'];
            }elseif( $shop_id != $v['shop_id'] ){
                continue;
            }

            $goodsInfo = $GoodsModel->where([
                "goods_id" => $v['goods_id']
            ])->field($GoosField)->find();
            
            if( !$goodsInfo )
            {
                $cartModel->where([
                    "goods_id" => $v['goods_id']
                ])->setField(array('status' => 0, 'selected' => 0));

                if( $invalid_chk )
                {
                    throw new \Exception("商品不存在:".$v['goods_id'],-1);
                }
                continue;
            }

            if( !$goodsInfo['is_on_sale'] )
            {
                $cartModel->where([
                    "goods_id" => $v['goods_id']
                ])->setField(array('status' => 0, 'selected' => 0));
                
                if( $invalid_chk )
                {
                    throw new \Exception("商品{$goodsInfo['goods_name']}已失效",-1);
                }
                continue;                
            }

            #商品价格
            if($goodsInfo['prom_type'] && $goodsInfo['prom_id']) {
                if ($goodsInfo['prom_type'] == 1) 
                {
                    //限时抢购
                    $kill = M('flash_sale')
                        ->field('price')
                        ->where([
                            "goods_id" => $goodsInfo['goods_id']
                        ])
                        ->find();
                    $price = $kill['price'];
                } elseif ($goodsInfo['prom_type'] == 2) 
                {   
                    #团购的询价体系不在这里
                    $price = $goodsInfo['shop_price'];
                } else {//品牌清仓
                    $where['goods_id'] = $goods_id;
                    $where['id'] = $goodsInfo['prom_id'];
                    $qin = M("prom_goods as p")
                        ->field('p.type,g.shop_price,p.expression')
                        ->where($where)
                        ->join('ln_goods as g on g.prom_id=p.id')
                        ->find();
                    if ($qin['type'] == 0) {
                        $price = bcmul($qin['shop_price'], $qin['expression'] /100 , 2 );//打折优惠
                    } else {
                        $price = bcsub($qin['shop_price'],$qin['expression'],2);//减价优惠
                    }
                }
            } else {
                $price = $goodsInfo['shop_price'];
            }
            #单商品小计
            $v['goods_fee'] = bcmul($v['goods_num'],$price,3);

            #商品总数
            $anum += $v['goods_num'];

            #商品总价
            $goods_price = bcadd($goods_price,$v['goods_fee'],2);

            #看看商品是否免邮费
            if( !isset($goodsInfo['is_free_shipping']) || $goodsInfo['is_free_shipping'] == 0 )
            {
                $goods_weight += $goodsInfo['weight'];
            }
        }

        $total = [
            'total_amount' => $total_amount, // 订单总价(商品+运费)
            'order_amount' => $order_amount, // 应付金额（订单总价-优惠-抵扣）
            'shipping_price' => $shipping_price, // 物流费
            'goods_price' => $goods_price, // 商品总价
            'cut_fee' => $cut_fee, // 共节约多少钱
            'anum' => $anum, // 商品总共数量
            'integral_money' => $pay_points,  // 积分抵消金额
            'order_goods' => $order_goods, // 商品列表 多加几个字段原样返回
            'count_is_prom' => $is_prom,     //购买商品中存在优惠活动商品数量
            'all_pay_point' => $all_pay_point,      //允许使用最大积分
            'available_points' => $user['pay_points'],//用户可用的积分
            'uncharge_amount' => $order_amount_uncharge,
        ];
    }

    /**
     * 根据商品总重量计算邮费(以商铺为单位)
     * @param shop_id 商铺id
     * @param weight 商品总重量 克
     * @param goods_fee 商品总价
     * @return float
     */
    public static function getPostFeeNew( $shop_id = 0, $weight = 0, $goods_fee = 0 ,$juli = 0)
    {

        $dada_distance = tpCache('shopping.dd_distance');

        if($juli > 0 && $juli <= bcmul($dada_distance, 1000)){

            return tpCache('shopping.dd_exp_fee');
        }

        $conf = self::getShopPostFeeSettings($shop_id);

        $logText = "\n[PARAMS]".json_encode(func_get_args());

        $logText .= "\n[CONF]".json_encode($conf);

        doLog($logText,'postfee');

        if(!$conf) return 0;

        if( $conf['fee_freepost'] > 0 && $goods_fee >= $conf['fee_freepost'] )
        {
            return 0;
        }

        #计算首重价格
        $f_price = $conf['default_postfee'];

        #如果续重为0或者续费为0
        if( $weight <= $conf['first_weight'] || $conf['second_weight'] < 1 || $conf['add_postfee'] < 0 )
        {
            return $f_price;
        }

        #计算续重
        $weight = $weight - $conf['first_weight'];
        $m_w = ceil( $weight /  $conf['second_weight'] );

        if( $m_w <= 0 )
            return $f_price;

        return $f_price + $m_w * $conf['add_postfee'];
    }
}